package com.bc.plugin.doc.resolver.help;

import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaField;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaClassUtil {

    private static final String CLAZZ_PATTERN = "(\\w+\\.)+\\w+(\\[\\])?";
    private static final String SIMPLE_GENERIC_CLASS_PATTERN = CLAZZ_PATTERN + "(<" + CLAZZ_PATTERN + "(," + CLAZZ_PATTERN + ")*>)?(\\[\\])?";
    private static final String GENERIC_CLASS_PATTERN = CLAZZ_PATTERN + "(<" + SIMPLE_GENERIC_CLASS_PATTERN + "(," + SIMPLE_GENERIC_CLASS_PATTERN + ")*>)?(\\[\\])?";
    private static Pattern pattern = Pattern.compile(GENERIC_CLASS_PATTERN);

    public static List<String> getGenericTypes(String className) {
        int index = className.indexOf("<");
        if (index < 0) {
            return null;
        }
        String genericTypes = className.substring(index + 1, className.lastIndexOf(">"));
        List<String> fieldTypeList = new ArrayList<>();
        if (!genericTypes.contains(",")) {
            fieldTypeList.add(genericTypes);
            return fieldTypeList;
        }

        Matcher matcher = pattern.matcher(genericTypes);
        while (matcher.find()) {
            String result = matcher.group();
            fieldTypeList.add(result);
        }

        return fieldTypeList;
    }

    /**
     * Get fields
     *
     * @param cls1 The JavaClass object
     * @return list of JavaField
     */
    public static List<JavaField> getFields(JavaClass cls1) {
        List<JavaField> fieldList = new ArrayList<>();
        if (null == cls1) {
            return fieldList;
        } else if ("Object".equals(cls1.getSimpleName()) || "Timestamp".equals(cls1.getSimpleName())
                || "Date".equals(cls1.getSimpleName()) || "Locale".equals(cls1.getSimpleName())) {
            return fieldList;
        } else {
            JavaClass pcls = cls1.getSuperJavaClass();
            fieldList.addAll(getFields(pcls));
            fieldList.addAll(cls1.getFields());
        }
        return fieldList;
    }
}
